package org.dromara.web.CssUtil.payUtil;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 生成加密明文工具类
 */
public class ClearTextUtil {

	/** 参数分隔符 */
	public static final String SIGNATURE_SEPARATOR = "&";

	/**
	 * 生成待加密的明文，排除signature字段，包括空字段
	 * @param obj
	 * @return
	 */
	public static String generateClearText(Object obj){
		List<String> excludeFieldList = new ArrayList<>();
		excludeFieldList.add("signature");
		return generateClearText(obj, excludeFieldList);
	}

	/**
	 * 生成加密的明文
	 * @param obj	需要签名的bean
	 * @param excludeFieldList	需要参与签名的字段名列表
	 * @return
	 */
	public static String generateClearText(Object obj, List<String> excludeFieldList) {
		return generateClearText(obj, excludeFieldList, true);
	}

	public static String generateClearTextExcludeNullField(Object obj, List<String> excludeFieldList){
		return generateClearText(obj, excludeFieldList, false);
	}

	public static String generateClearText(Object obj, List<String> excludeFieldList, Boolean includeNullField){
		if(obj == null){
			throw new RuntimeException("参数不合法");
		}

		List<String> fieldList = ReflectUtil.getPrivateFields(obj.getClass(), excludeFieldList);
		if(CollectionUtils.isEmpty(fieldList)){
			throw new RuntimeException("参与签名的字段异常");
		}

		/** 对参与签名的字段名排序 */
		Collections.sort(fieldList);
		StringBuffer sb = new StringBuffer();

		/** 拼接签名字符串 */
		for (String fieldName : fieldList) {
			Object value = ReflectUtil.getFieldValue(fieldName, obj);
			String s = appendField(fieldName, value, includeNullField);
			sb.append(s);
		}

		return sb.substring(0, sb.length() - 1);	//返回结果需去掉最后一个分隔符
	}


	private static String appendField(String fieldName, Object value, Boolean includeNullField){
		StringBuffer sb = new StringBuffer();

		if(value == null || "".equals(value)){
			if(!includeNullField){
				return "";
			}
			sb.append(fieldName).append("=");
		}else{
			sb.append(fieldName).append("=").append(value);
		}

		sb.append("&");
		return sb.toString();
	}

}
